
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Xml.Linq;
using Microsoft.AspNetCore.Mvc;
using ST.Core;
using ST.Data;
using ST.ModelVM;
using ST.ModelVM.ProtocolDefine;
using ST.ModelVM.ProtocolSim;
 

namespace ST.Simulator.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class ProtocolSimController : ControllerBase
    {
        IRepository<Data.ProtocolDefine> _IProtocolDefineRepository;
        IRepository<Data.ProtocolSim> _IRepository;
        IRepository<Data.ProtocolSimHost> _IRepositoryProtocolSimHost;

      

        public ProtocolSimController(IRepository<Data.ProtocolDefine> repository1,
            IRepository<Data.ProtocolSim> repository2,
            IRepository<Data.ProtocolSimHost> repository3)
        {
            _IProtocolDefineRepository = repository1;
            _IRepository = repository2;
            _IRepositoryProtocolSimHost=repository3;
        }
        public static string GetRunState(long Id)
        {
            return ST.Receiver.Tasks.TransMain.Instance.GetRunState(Id);             
        }
        [HttpGet("Tree")]
        [HttpPost("Tree")]

        public List<KendoTreeViewNode> Tree()
        {
             
            var ldefine = _IProtocolDefineRepository.GetAll()
                    .Select(a => new ProtocolDefine { Id = a.Id, Name = a.Name })
                    .ToList(); 
            var lsim = _IRepository.GetAll()
                .ToList();
            var lsimhost = _IRepositoryProtocolSimHost.GetAll().Select(a => new ProtocolSimHost
            {
                Id=a.Id,
                 ProtocolSimId=a.ProtocolSimId,
                HostName=a.HostName,
                HostId=a.HostId,    
            }).ToList();
            var r=new List<KendoTreeViewNode>();
            foreach(var msim in lsim)
            {
                var tn = new KendoTreeViewNode
                {
                    id = msim.Id.ToString(),
                    text = msim.Name + $" ({GetRunState(msim.Id)})",
                    expanded = true,
                    hasChildren = true,
                    imageurl = msim.Mode == "UDP" ? "fa fa-podcast" : 
                     msim.Mode == "TCP" ? "fa fa-id-card" : 
                     "fa fa-microchip", // 根据模式设置
                    attrs1=msim.Mode,
                    attrs2="A"

                };
                r.Add(tn);
                var lhost=lsimhost.Where(a=>a.ProtocolSimId==msim.Id)
                    .OrderBy(a=>a.HostId).ToList();
                foreach(var mhost in lhost)
                {
                    var tnhost = new KendoTreeViewNode
                    {
                        id = mhost.Id.ToString(),
                        text = mhost.HostName,
                        expanded = true,
                        hasChildren = false,
                        imageurl = "fa fa-server" ,// 主机图标
                        attrs1="主机",
                        attrs2="B"
                    };
                    tn.items.Add(tnhost);
                }
            }
            return r;
        }

        [HttpPost("Add")]
        public ProtocolSimVM Add(ProtocolSimVM mm){
            
            var mdefine = _IProtocolDefineRepository.GetById(mm.ProtocolDefineId);
            var mdefineVM = ST.Core.Util.JSON.DeserializeObject<ModelVM.ProtocolDefine.ProtocolDefineVM>(mdefine.Content);
            var m = new ProtocolSim();
            mm.Id = ST.Core.Util.IdUtil.NextId();
            m.Id = mm.Id;
            m.Name = mm.Name;
            m.ProtocolDefineId = mm.ProtocolDefineId;
            
            m.Mode = mm.Mode;
            m.ComPort = mm.ComPort;
            m.BaudRate = mm.BaudRate;
            m.DataBits = mm.DataBits;
            m.Parity = mm.Parity;
            m.StopBits = mm.StopBits;
            m.IP = mm.IP;

            m.Port = mm.Port;
            m.CrtDt = DateTime.Now;
            m.EdtDt = DateTime.Now; 
            _IRepository.DB.Add(m);

            var mhost=new ProtocolSimHost();
            mhost.Id= ST.Core.Util.IdUtil.NextId();
            mhost.ProtocolSimId = m.Id;
            mhost.HostId = 1;
            mhost.HostName = $"机号：{mhost.HostId}";
          
            mhost.Content = ST.Core.Util.JSON.SerializeObject(mdefineVM.ZSBCS);

            mhost.CrtDt = DateTime.Now;
            mhost.EdtDt = DateTime.Now;
            _IRepository.DB.Add(mhost);

            _IRepository.DB.SaveChanges();

            return mm;
        }


        [HttpPost("Edit")]
        public ProtocolSimVM Edit(ProtocolSimVM mm)
        {
          
           
            var m = _IRepository.GetById(mm.Id);
           
            m.Name = mm.Name;
            m.ProtocolDefineId = mm.ProtocolDefineId;

            m.Mode = mm.Mode;
            m.ComPort = mm.ComPort;
            m.BaudRate = mm.BaudRate;
            m.DataBits = mm.DataBits;
            m.Parity = mm.Parity;
            m.StopBits = mm.StopBits;

            m.IP = mm.IP;
            m.Port = mm.Port;
          
            m.EdtDt = DateTime.Now;
           

            _IRepository.DB.SaveChanges();

            return mm;
        }

        [HttpPost("Delete")]
        public async Task<Data.ProtocolSim> Delete(Int64Model mm)
        {
            var m = _IRepository.GetById(mm.Id);
            _IRepository.DB.Remove(m);
            var lhost = _IRepositoryProtocolSimHost.GetAll()
                .Where(a => a.ProtocolSimId == m.Id).ToList();
            foreach(var mhost in lhost)
            {
                _IRepository.DB.Remove(mhost);
            }
            await _IRepository.DB.SaveChangesAsync();
            return m;
        }


        [HttpPost("Detail")]
        public ProtocolSimVM Detail(Int64Model qm)
        {
            var mdb = _IRepository.GetById(qm.Id);
            var m = new ProtocolSimVM();
            m.Id = mdb.Id;
            m.Name = mdb.Name;
            m.ProtocolDefineId = mdb.ProtocolDefineId;
            m.ProtocolName = _IProtocolDefineRepository.GetById(mdb.ProtocolDefineId).Name;
            m.RunState = GetRunState(m.Id);
            m.Mode = mdb.Mode;
            m.ComPort = mdb.ComPort;
            m.BaudRate = mdb.BaudRate;
            m.DataBits = mdb.DataBits;
            m.Parity = mdb.Parity;
            m.StopBits = mdb.StopBits;

            m.IP = mdb.IP;
            m.Port = mdb.Port;


            if (m.Mode == "串口")
            {
                m.ModeMessage = $"{m.Mode}:{m.BaudRate} {m.Parity} {m.DataBits} {m.StopBits}";
            }
            else
            {
                m.ModeMessage = $"{m.Mode}:{m.Port}";
            }
            return m;
        }

        [HttpPost("StartSim")]
        public async Task<Int64Model> StartSim(Int64Model qm)
        {
            await ST.Receiver.Tasks.TransMain.Instance.StartSimAsync(qm.Id);
            return qm;
        }

        [HttpPost("StopSim")]
        public async Task<Int64Model> StopSim(Int64Model qm)
        {
            await ST.Receiver.Tasks.TransMain.Instance.StopSimAsync(qm.Id);
            return qm;
        }










    }
}